﻿
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using LPP.Entity.Orders;
using LPP.EntityFrameworkCore;
using LPP.Core.Dtos;
using Microsoft.Extensions.Logging;

namespace LPP.Repository.Repositories
{
    public class OrderRepository : IOrderRepository
    {
        private readonly SqlDbContext _context;
        private readonly ILogger<OrderRepository> _logger;

        public OrderRepository(SqlDbContext context, ILogger<OrderRepository> logger)
        {
            _context = context;
            _logger = logger;
        }

        // 事务相关
        public async Task<IDbContextTransaction> BeginTransactionAsync()
        {
            return await _context.Database.BeginTransactionAsync();
        }

        // 订单基础操作
        public async Task<Order> GetOrderByIdAsync(string orderId)
        {
            return await _context.Orders
                .Include(o => o.OrderDetails)
                .FirstOrDefaultAsync(o => o.OrderID == orderId);
        }

        public async Task<List<Order>> GetUserOrdersAsync(int userId)
        {
            return await _context.Orders
                .Where(o => o.UserID == userId)
                .Include(o => o.OrderDetails)
                .ToListAsync();
        }
        public async Task<IEnumerable<Order>> GetOrdersByWorkerIdAsync(int workerId)
        {
            return await _context.Orders
                .Include(o => o.OrderDetails)
                .Where(o => o.WorkerID == workerId)
                .OrderByDescending(o => o.CreatedAt)
                .ToListAsync();
        }

        public async Task UpdateOrderAsync(Order order)
        {
            _context.Orders.Update(order);
            await _context.SaveChangesAsync();
        }

        public async Task AddOrderAsync(Order order)
        {
            await _context.Orders.AddAsync(order);
            await _context.SaveChangesAsync();
        }

        // 订单明细操作
        public async Task InsertOrderDetailAsync(OrderDetail orderDetail)
        {
            await _context.OrderDetails.AddAsync(orderDetail);
            await _context.SaveChangesAsync();
        }

        public async Task<List<OrderDetail>> GetUnfinishedOrderDetailsAsync()
        {
            return await _context.OrderDetails
                .Where(od => od.Status == OrderStatus.Pending)
                .ToListAsync();
        }

        // 工人相关查询
        public async Task<int> GetWorkerPendingOrdersCountAsync(int workerId)
        {
            return await _context.Orders
                .CountAsync(o => o.WorkerID == workerId && o.Status == OrderStatus.Pending);
        }
     

        public async Task<IEnumerable<Order>> GetWorkerCompletedOrdersAsync(int workerId, DateTime? startDate, DateTime? endDate)
        {
            return await _context.Orders
                .Where(o => o.WorkerID == workerId && o.Status == OrderStatus.Completed)
                .ToListAsync();
        }

        // 订单状态查询
        public async Task<IEnumerable<Order>> GetCompletedOrdersAsync(DateTime? startDate, DateTime? endDate)
        {
            return await _context.Orders
                .Where(o => o.Status == OrderStatus.Completed)
                .ToListAsync();
        }
        public async Task<int> GetCompletedOrdersCountAsync()
        {
            return await _context.Orders
                .CountAsync(o => o.Status == OrderStatus.Completed);
        }
        public async Task<WorkerIncomeStatisticsDto> GetWorkerIncomeStatisticsAsync(int workerId)
        {
            
            try
            {
                // 只查询需要的字段，避免查询 NotMapped 的属性
                var worker = await _context.Workers
                    .Where(w => w.WorkerID == workerId)
                    .Select(w => new
                    {
                        w.WorkerID,
                        OrderDetails = w.OrderDetails
                            .Where(od => od.Order.Status == OrderStatus.Completed ||
                                        od.Order.Status == OrderStatus.Reviewed)
                            .Select(od => new
                            {
                                od.TotalPrice,
                                od.Order.CompletedTime
                            })
                    })
                    .FirstOrDefaultAsync();

                if (worker == null)
                    return null;

                var now = DateTime.Now;
                var today = now.Date;
                var yesterday = today.AddDays(-1);
                var weekStart = today.AddDays(-(int)today.DayOfWeek);
                var monthStart = new DateTime(now.Year, now.Month, 1);
                var quarterStart = new DateTime(now.Year, ((now.Month - 1) / 3) * 3 + 1, 1);
                var yearStart = new DateTime(now.Year, 1, 1);

                // 计算工人收入（默认抽成比例50%）
                decimal CalculateWorkerIncome(decimal totalPrice) => totalPrice * 0.5m;

                return new WorkerIncomeStatisticsDto
                {
                    MonthlyIncome = worker.OrderDetails
                        .Where(od => od.CompletedTime >= monthStart)
                        .Sum(od => CalculateWorkerIncome(od.TotalPrice)),

                    YesterdayIncome = worker.OrderDetails
                        .Where(od => od.CompletedTime?.Date == yesterday)
                        .Sum(od => CalculateWorkerIncome(od.TotalPrice)),

                    WeeklyIncome = worker.OrderDetails
                        .Where(od => od.CompletedTime >= weekStart)
                        .Sum(od => CalculateWorkerIncome(od.TotalPrice)),

                    QuarterlyIncome = worker.OrderDetails
                        .Where(od => od.CompletedTime >= quarterStart)
                        .Sum(od => CalculateWorkerIncome(od.TotalPrice)),

                    YearlyIncome = worker.OrderDetails
                        .Where(od => od.CompletedTime >= yearStart)
                        .Sum(od => CalculateWorkerIncome(od.TotalPrice)),

                    TotalIncome = worker.OrderDetails
                        .Sum(od => CalculateWorkerIncome(od.TotalPrice))
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工人收入统计失败");
                throw;
            }
        }
        public async Task<(int Total, IEnumerable<OrderBillDto> Bills)> GetWorkerBillsAsync(
       int workerId,
       DateTime? startDate,
       DateTime? endDate,
       int page,
       int pageSize)
        {
            try
            {
                var query = _context.OrderDetails
                    .Include(od => od.Order)
                    .Where(od => od.WorkerID == workerId);

                if (startDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime >= startDate);

                if (endDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime <= endDate);

                var total = await query.CountAsync();
                var bills = await query
                    .OrderByDescending(od => od.Order.CompletedTime)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .Select(od => new OrderBillDto
                    {
                        OrderDetailID = od.OrderDetailID,
                        OrderID = od.Order.OrderID,
                        CompletedTime = od.Order.CompletedTime,
                        TotalPrice = od.TotalPrice,
                        Status = od.Order.Status,
                        ProductName = od.ProductName,
                        Rating = od.Rating
                    })
                    .ToListAsync();

                return (total, bills);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工人账单明细失败");
                throw;
            }
        }

        public async Task<PlatformIncomeStatisticsDto> GetPlatformIncomeStatisticsAsync(
     DateTime? startDate,
     DateTime? endDate)
        {
            try
            {
                var query = _context.OrderDetails
                    .Include(od => od.Order)
                    .Where(od => od.Order.Status == OrderStatus.Completed ||
                                od.Order.Status == OrderStatus.Reviewed);

                if (startDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime >= startDate);

                if (endDate.HasValue)
                    query = query.Where(od => od.Order.CompletedTime <= endDate);

                var result = await query
                    .Select(od => new
                    {
                        od.TotalPrice,
                        od.WorkerID
                    })
                    .ToListAsync();

                // 计算平台收入（默认抽成比例50%）
                decimal CalculatePlatformIncome(decimal totalPrice) => totalPrice * 0.5m;

                return new PlatformIncomeStatisticsDto
                {
                    TotalIncome = result.Sum(od => CalculatePlatformIncome(od.TotalPrice)),
                    OrderCount = result.Count,
                    WorkerCount = result.Select(od => od.WorkerID).Distinct().Count()
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取平台收入统计失败");
                throw;
            }
        }

        // 已实现的分页相关方法保持不变
        public async Task<IEnumerable<Order>> GetCompletedOrdersAsync(int pageIndex, int pageSize)
        {
            return await _context.Orders
                .Where(o => o.Status == OrderStatus.Completed)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
        }

        public async Task<IEnumerable<Order>> GetWorkerCompletedOrdersAsync(int workerId, int pageIndex, int pageSize)
        {
            return await _context.Orders
                .Where(o => o.WorkerID == workerId && o.Status == OrderStatus.Completed)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
        }
        public async Task<int> GetWorkerCompletedOrdersCountAsync(int workerId)
        {
            return await _context.Orders
                .CountAsync(o => o.WorkerID == workerId && o.Status == OrderStatus.Completed);
        }

    }
}

